package com.applcn.file.utils;

import cn.hutool.core.util.StrUtil;
import com.applcn.file.apollo.CosConfig;
import com.applcn.file.enums.FileChoiceEnum;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.region.Region;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.URL;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class CosUtil implements AbstractFileUtil {

    private final int code = FileChoiceEnum.COS.getCode();
    private COSClient cosClient;

    private final CosConfig cosConfig;

    @Override
    public Integer getIdentification() {
        return code;
    }

    @PostConstruct
    private void init() {
        if (cosClient == null) {
            synchronized (COSClient.class) {
                if (cosClient == null) {
                    // 1 初始化用户身份信息（secretId, secretKey）。
                    COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
                    // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
                    // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
                    Region region = new Region(cosConfig.getRegion());
                    ClientConfig clientConfig = new ClientConfig(region);
                    // 3 生成 cos 客户端。
                    cosClient = new COSClient(cred, clientConfig);
                }
            }
        }
    }

    /**
     * 客户端获取上传凭证
     *
     * @return
     */
    public String getCertification(String fileName) {
        Date expirationTime = new Date(System.currentTimeMillis() + cosConfig.getExpire());
        URL url = cosClient.generatePresignedUrl(cosConfig.getDefaultBucketName(), fileName, expirationTime, HttpMethodName.PUT);
        return url.toString();
    }

    @Override
    public String getFileUrl(String fileName) {
        return cosConfig.getDomain() + "/" + fileName;
    }
}
